from flask import Blueprint, jsonify, request
from ..models.aircraft import Aircraft
from .. import db

bp = Blueprint('aircraft', __name__, url_prefix='/api/aircraft')

# 定义角色映射
ROLE_MAPPINGS = {
    '对空': {'value': '对空', 'label': '对空作战'},
    '对地': {'value': '对地', 'label': '对地攻击'},
    '反潜': {'value': '反潜', 'label': '反潜巡逻'},
    '电子干扰': {'value': '电子干扰', 'label': '电子干扰'},
    '空运': {'value': '空运', 'label': '空中运输'},
    '预警指挥': {'value': '预警指挥', 'label': '预警指挥'}
}

@bp.route('/roles', methods=['GET'])
def get_roles():
    """获取所有可用的飞机角色"""
    roles = [
        {'value': role['value'], 'label': role['label']}
        for role in ROLE_MAPPINGS.values()
    ]
    return jsonify(roles)

@bp.route('', methods=['GET'])
def get_aircraft():
    """获取飞机列表，支持按角色筛选"""
    role = request.args.get('role')
    query = Aircraft.query
    
    if role:
        query = query.filter(Aircraft.role == role)
    
    aircraft_list = query.all()
    return jsonify([{
        'id': aircraft.id,
        'name': aircraft.name,
        'length': aircraft.length,
        'width': aircraft.width,
        'role': aircraft.role
    } for aircraft in aircraft_list])

@bp.route('/<int:id>', methods=['GET'])
def get_single_aircraft(id):
    """获取单个飞机信息"""
    aircraft = Aircraft.query.get_or_404(id)
    return jsonify({
        'id': aircraft.id,
        'name': aircraft.name,
        'length': aircraft.length,
        'width': aircraft.width,
        'role': aircraft.role
    })

@bp.route('', methods=['POST'])
def create_aircraft():
    """创建新飞机"""
    data = request.get_json()
    if data['role'] not in ROLE_MAPPINGS:
        return jsonify({'error': '无效的飞机角色'}), 400
        
    aircraft = Aircraft(
        name=data['name'],
        length=data['length'],
        width=data['width'],
        role=data['role']
    )
    db.session.add(aircraft)
    db.session.commit()
    return jsonify(aircraft.to_dict()), 201

@bp.route('/<int:id>', methods=['PUT'])
def update_aircraft(id):
    """更新飞机信息"""
    aircraft = Aircraft.query.get_or_404(id)
    data = request.get_json()
    
    if 'role' in data and data['role'] not in ROLE_MAPPINGS:
        return jsonify({'error': '无效的飞机角色'}), 400
    
    aircraft.name = data.get('name', aircraft.name)
    aircraft.length = data.get('length', aircraft.length)
    aircraft.width = data.get('width', aircraft.width)
    aircraft.role = data.get('role', aircraft.role)
    
    db.session.commit()
    return jsonify(aircraft.to_dict())

@bp.route('/<int:id>', methods=['DELETE'])
def delete_aircraft(id):
    """删除飞机"""
    aircraft = Aircraft.query.get_or_404(id)
    db.session.delete(aircraft)
    db.session.commit()
    return '', 204 